const _ = require('lodash');
const moment = require('moment');

const prefix = '/api/schedule';

module.exports = (app) => {
    const {router, middleware} = app;

    /**mode= project anchor project_anchor 三种情况的直播记录查询*/
    const query = async ctx => {
        const {or, between} = ctx.app.Sequelize.Op;

        let {offset, limit} = ctx.service.page.page();

        let order = ctx.query.order === '1' ? 'desc' : 'asc';

        let {start, end} = ctx.query;
        let {project_id, anchor_id} = ctx.params;

        if (start)
            start = moment(start).startOf('day').toDate();
        else
            start = moment().startOf('day').toDate();

        if (end)
            end = moment(end).endOf('day').toDate();
        else
            end = moment().endOf('day').toDate();

        const sql = {
            where: {[or]: [{start: {[between]: [start, end]}}, {end: {[between]: [start, end]}}]},
            limit,
            offset,
            include: [],
            order: [['end', order]],
        };
        const count = {
            where: {[or]: [{start: {[between]: [start, end]}}, {end: {[between]: [start, end]}}]},
        };

        if (project_id) {
            sql.where['project_id'] = project_id;
            count.where['project_id'] = project_id;
            sql.include.push({model: ctx.app.model.Platform});
            sql.include.push({model: ctx.app.model.DetailAnchor, as: 'anchor'});
        }
        if (anchor_id) {
            sql.where['anchor_id'] = anchor_id;
            count.where['anchor_id'] = anchor_id;
            sql.include.push({model: ctx.app.model.Project, as: 'project'});
        }

        if (project_id && anchor_id) {
            delete sql.include;
        }

        ctx.body = {
            list: await app.model.DetailAnchorSchedule.findAll(sql),
            total: await app.model.DetailAnchorSchedule.count(count),
        };
    };
    router.get(prefix + '/anchor/:anchor_id', middleware.api(4), query);
    router.get(prefix + '/project/:project_id', middleware.api(4), query);
    router.get(prefix + '/project/:project_id/anchor/:anchor_id', middleware.api(4), query);

    /**读取 单一 直播记录 信息*/
    router.get(prefix + '/:schedule_id', middleware.api(4), async ctx => {
        const {schedule_id} = ctx.params;
        let schedule = await ctx.app.model.DetailAnchorSchedule.findOne({
            where: {id: schedule_id},
            include: [{model: app.model.File, as: 'image', required: false,}],
        });
        if (!schedule)
            return ctx.helper.error('不存在的直播记录');
        const [project, platform, anchor, images] = await Promise.all([
            ctx.app.model.Project.findByPk(schedule.project_id),
            ctx.app.model.Platform.findByPk(schedule.platform_id),
            ctx.app.model.DetailAnchor.findByPk(schedule.anchor_id),
            app.model.File.findAll({
                where: {selected: true,},
                include: [{
                    as: 'scheduleImage',
                    model: app.model.DetailScheduleImage,
                    where: {
                        anchor_id: schedule.anchor_id,
                        schedule_id,
                    }
                }],
            }),
        ]);
        schedule = schedule.toJSON();
        schedule.selected_anchor_image_id = _.map(images, 'id');

        ctx.body = {project, platform, anchor, schedule};
    });

    /**读取 单一 直播记录 的所有主播截图*/
    router.get(prefix + '/:schedule_id/anchor_image', middleware.api(4), async ctx => {
        const {schedule_id} = ctx.params;
        const schedule = await app.model.DetailAnchorSchedule.findByPk(schedule_id);
        if (!schedule)
            return ctx.helper.error('不存在的直播记录');
        ctx.body = await app.model.File.findAll({
            include: [{
                as: 'scheduleImage',
                model: app.model.DetailScheduleImage,
                where: {
                    anchor_id: schedule.anchor_id,
                    schedule_id,
                    platform_id: schedule.platform_id,
                }
            }]
        });
    });

    /**读取 平台截图记录*/
    router.get(prefix + '/:schedule_id/platform_image', middleware.api(4), async ctx => {
        const {schedule_id} = ctx.params;
        const schedule = await ctx.app.model.DetailAnchorSchedule.findByPk(schedule_id);
        if (!schedule)
            return ctx.helper.error('不存在的直播记录');
        ctx.body = await app.model.File.findAll({
            include: [{
                as: 'scheduleImage',
                model: app.model.DetailScheduleImage,
                where: {
                    anchor_id: null,
                    schedule_id,
                    platform_id: schedule.platform_id,
                }
            }]
        });
    });

    /**添加直播记录*/
    router.post(prefix, middleware.api(4), async ctx => {
        const data = ctx.request.body;
        if (!data.anchor || !data.anchor.id)
            return ctx.helper.error('缺少主播数据');
        if (!data.anchor.platform_id)
            return ctx.helper.error('缺少平台数据');
        if (!data.project_id)
            return ctx.helper.error('缺少项目数据');
        if (!(data.loop > 1))
            data.loop = 1;
        const {project_id, anchor} = data;

        data.anchor_id = data.anchor.id;
        data.platform_id = data.anchor.platform_id;
        delete data.id;

        if (_.isEmpty(data.start) || _.isEmpty(data.end))
            return ctx.helper.error('缺少直播记录的时间数据');

        let schedule = await app.model.DetailAnchorSchedule.create(data);

        if (0 === await app.model.ProjectAnchor.count({where: {project_id, anchor_id: anchor.id}}))
            await app.model.ProjectAnchor.create({project_id, anchor_id: anchor.id});

        ctx.body = await app.model.DetailAnchorSchedule.findOne({
            where: {id: schedule.id},
            include: [{model: app.model.DetailAnchor, as: 'anchor', include: [{model: app.model.Platform}]}]
        });

        ctx.service.event.add({
            anchor: {id: data.anchor_id},
            project: {id: data.project_id},
            content: '添加直播记录'
        });
    });

    /**修改 直播记录*/
    router.post(prefix + '/:schedule_id', middleware.api(4), async ctx => {
        const {schedule_id} = ctx.params;
        let schedule = await app.model.DetailAnchorSchedule.findByPk(schedule_id);
        if (!schedule)
            return ctx.helper.error('不存在的直播记录');
        const data = ctx.request.body;
        let images = await ctx.app.model.File.findAll({
            include: [{
                as: 'scheduleImage',
                model: app.model.DetailScheduleImage,
                where: {
                    schedule_id: schedule.id,
                }
            }]
        });

        if (_.isEmpty(data.start) || _.isEmpty(data.end))
            return ctx.helper.error('缺少直播记录的时间数据');


        if (!_.isEmpty(images) && !_.isEmpty(data.selected_anchor_image_id))
            images.forEach(image => {
                let selected = data.selected_anchor_image_id.indexOf(image.id) >= 0;
                image.update({selected});
                image.scheduleImage.update({selected});
            });

        ctx.service.event.add({
            anchor: {id: schedule.anchor_id},
            project: {id: schedule.project_id},
            content: '修改直播记录'
        });
        if (data.image_id >= 0) {
            let image = _.find(images, {id: data.image_id});
            if (image) {
                image.update({selected: true});
                image.scheduleImage.update({selected: true});
            }
            else
                data.image_id = null;
        } else {
            images.forEach(image => {
                if (image.anchor_id === null)
                    image.update({selected: false});
            });
            data.image_id = null;
        }

        await schedule.update({
            qrcode: !!data.qrcode,
            loop: data.loop > 1 ? data.loop : 1,
            start: data.start,
            end: data.end,
            online: data.online > 0 ? data.online : 0,
            cost: data.cost,
            added: data.added,
            click: data.click,
            reflux: data.reflux,
            image_id: data.image_id,
        });
        ctx.body = 'ok';
    });

    /**删除平台截图*/
    router.del(prefix + '/:schedule_id/platform_image', middleware.api(4), async ctx => {
        const {schedule_id} = ctx.params;
        const schedule = await app.model.DetailAnchorSchedule.findByPk(schedule_id);
        if (!schedule)
            return ctx.helper.error('不存在的直播记录');
        schedule.update({image_id: null});
        ctx.body = 'ok';
    });

    /**删除直播记录*/
    router.del(prefix + '/:schedule_id', middleware.api(4), async ctx => {
        const {schedule_id} = ctx.params;
        const schedule = await ctx.app.model.DetailAnchorSchedule.findOne({
            where: {id: schedule_id},
            include: [
                {model: app.model.File, as: 'images', required: false,},
                {model: app.model.File, as: 'image', required: false},
            ]
        });
        if (!schedule)
            return ctx.helper.error('不存在的直播记录');

        //将所有截图都重置为没有使用的状态
        let imageId = [];
        if (schedule.image && schedule.image.id > 0)
            imageId.push(schedule.image.id);
        if (schedule.images && schedule.images.length > 0)
            imageId.push(...schedule.images.map(image => image.id));
        app.model.File.update({selected: false}, {where: {id: {[app.Sequelize.Op.in]: imageId}}});

        ctx.service.event.add({
            content: '删除直播记录',
            anchor: {id: schedule.anchor_id},
            project: {id: schedule.project_id},
        });

        await schedule.destroy();
        ctx.body = 'ok';
    });
};